<?php
/**
 *  Create On 2014-12-05
 *  Author yiwei
 *  QQ:1006629314
 **/
error_reporting(0);
class HomeworkController extends Controller{
	private $rootPath = "";		///var/www/html/howdo/
	private $targetPath = "common/upload/";
	private $uploadpath;
	private $send_mes;
	public function __construct() {
		parent::__construct ();
		$this->view->web_host = $this->getRequest ()->hostUrl;
		$this->view->web_app_url = $this->getRequest ()->hostUrl . "/clientapi.php";
		$this->uploadpath=$this->rootPath.$this->targetPath;
		//$this->logger = LoggerManager::getLogger('Homeworklog');
		$this->send_mes=$this->getRequest()->hostUrl. "/common/clientapi/images/50.png";
	}
	
	
	
	public function addHomework(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
		/*
		$str = '[{\"publish_type\":\"0\",\"id\":\"0\",\"period_id\":\"530\",\"publish_time\":\"2014.12.12 21:50:00\",\"action\":\"2\"},{\"publish_type\":\"0\",\"id\":\"0\",\"period_id\":\"39\",\"publish_time\":\"2014.12.12 21:50:00\",\"action\":\"2\"}]';
		$json = json_decode(stripslashes($str));
		var_dump($json);
		foreach($json as $key=>$val){
			var_dump($val['period_id']);
		}
		*/
		if($_POST){
			$homework = new homework();
			$homework_period = new homework_period();
			$json = $_POST;
			//提交模式：1-存为草稿，2-覆盖修改，3-新增/另存为
			$mode = $json['mode'];

			$item_id_str = $json['item_list'];
			$need_feedback = $json['need_feedback'];
			$item_num = $json['item_num'];
			$target_list = json_decode($json['target_list'],true);
			if($mode == 1){//作业状态为草稿
				if(array_key_exists('homeworkId', $json)){
					$homework_id = $json['homeworkId'];
					$homework_id = $homework->modifyHomework($homework_id, 2,
							$item_num, $item_id_str, $need_feedback);
				}else{
					$homework_id = $homework->addHomework($user_id,2,$item_num,
							$item_id_str, $need_feedback,'');
				}
			}else if($mode == 2){//作业的覆盖修改
				$homework_id = $json['homeworkId'];
				$homework->modifyHomework($homework_id,1, $item_num, $item_id_str, $need_feedback,'');
			}else if($mode == 3){//新建与另存为作业
				$homework_id = $homework->addHomework($user_id,1,$item_num,
						$item_id_str, $need_feedback,'');
			}
			if($target_list){
				foreach ($target_list as $val){
					if(!$val['publish_time']){
						
					}
					switch($val['action']){
						case -1://删除该项
							$homework_period->delHomeworkPeriod($val['id']);
							break;
						case 0://修改该项
						case 1:
							$homework_period->modifyHomeworkPeriod($val['period_id'],
							$homework_id,$val['publish_type'], $val['publish_time']);
							$find = $homework_period->getIdByPeriodId($val['period_id']);
							$id = $find['id'];
							break;
						case 2://新增该项
							$id = $homework_period->addHomeworkPeriod($homework_id,
							$val['period_id'], $val['publish_type'], $val['publish_time']);
							break;
					}					
					if(($val['action'] != -1) && ($val['publish_type'] == 2)){
						$homework_period->publishHomeworkPeriod($id);
						
						$message_list = $this->getApp()->loadConf("message");
						$message = new message();
						$class_student = new class_student();
						$stu_list = $class_student->getStudentIdByPeriod($val['period_id']);
						foreach ($stu_list as $keys=>$vals){
							$message->addMessage(MessageCodeEnum::MESSAGE_STU_NEW_HOMEWORK,$val['period_id'],
									MessageCodeEnum::getCodes(MessageCodeEnum::MESSAGE_STU_NEW_HOMEWORK),
									$user_id,$stu_list[$keys]['student_id']);
						}
					}
				}
			}	
			$data = array("mode"=>$mode,"homework_id"=>$homework_id,"targetlist"=>$target_list);		
			//$this->logger->error(json_encode($data));
			$this->view->setData ( $data );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "提交成功~" );
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "参数错误" );
		}
		$this->view->display ( "json" );
	}
	
	public function getHomework(){
		$id = $this->getRequest()->get('id');
		$item = new item();
		$homework = new homework();
		$homework_period = new homework_period();
		$result = $homework->getHomeworkById($id);
		if($result){
			$item_list = $item->getItemListByStr(1, $result['item_id_str']);
			$item_num = $result['item_num'];
			$need_feedback = $result['need_feedback'];
			$target_list = $homework_period->getHomeworkPeriod($id);
			//var_dump($target_list);
			if($target_list){
				foreach ($target_list as $key=>$val){
					$target_list[$key]['action'] = 0;
					$period = new period();
					$periodInfo = $period->getPeriodById($val['id']);
					$target_list[$key]['className'] = $periodInfo['className'];
					$target_list[$key]['section'] = $periodInfo['section'];
				}
			}else{
				$target_list = null;
			}
			$data = array("item_list"=>$item_list,"item_num"=>$item_num,"need_feedback"=>$need_feedback,"target_list"=>$target_list);
			//获取课程视频id
			
			$this->view->setData ( $data );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功~" );
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "作业不存在~" );
		}
		$this->view->display ( "json" );
	}
	
	public function getItemListByPeriod(){
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
	
		$period_id = $this->getRequest()->get('period_id'); 
		
		$homework_period = new homework_period();
		$homework_info=$homework_period->getHomeworkIdByPeriod($period_id);
		$homework_id=$homework_info["homework_id"];
		//$mode = $this->getRequest()->get('mode')?$this->getRequest()->get('mode'):0;
		if($homework_id){

			$homework = new homework();
			$result = $homework->getHomeworkById($homework_id);
			if($result){
				$preliststr = $result['item_id_str'];
				$prelist = explode('_', $preliststr);
				$teacher_id = $result['teacher_id'];
// 				var_dump($prelist);
				$item_feedback= new item_feedback();
				$itemcollection = new itemcollection();
				
				$video = new video();
				foreach($prelist as $key=>$val){
					$list[$key]['item_id'] = $val;
					$result = $video->getVideoByItem($teacher_id, $val, 1);
					if($result){
						$list[$key]['videoId'] = $result['id'];
						$list[$key]['videoStatue'] = 1;//有视频
					}else {
						$message = new message();
						if($message->hasSentMessage($user_id, MessageCodeEnum::MESSAGE_TEA_NO_VIDEO, $item_id)){
							$list[$key]['videoStatue'] = -1;//无视频但已经反馈过无视频
						}else{
							$list[$key]['videoStatue'] = 0;//无视频
						}
					}				
					$homework_item_feedback_info = $item_feedback->GetMyFeedbackByItemId($val, $homework_id, $user_id);
					if ($homework_item_feedback_info){
						if ($homework_item_feedback_info['feedback']){
							$list[$key]['feedbackStatue'] = 1;
						}else {
							$list[$key]['feedbackStatue'] = 0;
						}
					}else {
						$list[$key]['feedbackStatue'] = -1;
					}
// 					$list[$key]['feedbackStatue'] = $item_feedback->GetMyFeedbackByItemId($val, $homework_id, $user_id);
// 					if ($list[$key]['feedbackStatue']){
// 						if ($list[$key]['feedbackStatue']['feedback']){
// 							$list[$key]['feedbackStatue'] = 1;
// 						}else {
// 							$list[$key]['feedbackStatue'] = 0;
// 						}
// 					}else {
// 						$list[$key]['feedbackStatue'] = -1;
// 					}
					if($itemcollection->getCollectionItem($user_id, $val)){
						$list[$key]['collectionStatue'] = 1;
					}else{
						$list[$key]['collectionStatue'] = 0;
					}

				}
				$totalCount = count($list);
				$data = array('homework_id'=>$homework_id,'list'=>$list,'totalCount'=>$totalCount);
				$peroid=new period();
				$peroid_info=$peroid->getPeriodById($period_id);
				$data["course_video_id"]=$peroid_info["video_id"];
				$data["course_note_id"]=$peroid_info["note_id"];
				
				$this->view->setData ( $data );
				$this->view->setState ( "1" );
				$this->view->setMsg ( "获取成功" );
			}else{
				$this->view->setData ( null );
				$this->view->setState ( "0" );
				$this->view->setMsg ( "作业不存在~" );
			}
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "该课时无作业~" );
		}
		$this->view->display ( "json" ); 
	}
	
	
	public function getHomeworkDraftList(){
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
		//$user_id = 18;
		$homework = new homework();
		$list = $homework->getHomeworkDraft($user_id);
		if($list){
			$data = array("list"=>$list,"totalCount"=>count($list));
			$this->view->setData ( $data );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功" );
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "没有更多了哟" );
		}
		$this->view->display ( "json" ); 
	}
	
	public function delHomework(){
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
		$id = $this->getRequest()->get('id');
		$period_id = $this->getRequest()->get('periodId');
		
		if($period_id){
			$homework = new homework();
			$homework_period = new homework_period();
			$result = $homework_period->delHomeworkPeriodByPeriodId($period_id);
			if($result){
				$check = $homework_period->getHomeworkPeriod($id);
				//var_dump($check);
				if(!$check){
					$homework->delHomework($id);
				}
			}
		}else if($id){
			$homework = new homework();
			$result = $homework->delHomework($id);
		}
		if($result){
			$this->view->setData ( null );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "删除成功" );
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "删除失败~" );
		}
		$this->view->display ( "json" );
	}
	//学生端获取作业状态，state ，和image_count
	public function getHomeworkState(){
		$msg 	="";
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
		$homework_id=$this->getRequest()->get("homework_id");
		$homeworkFeedback=new homework_feedback();
		$homeworkFeedbackInfo=$homeworkFeedback->getMyHomeworkFeedbackByHomeworkId($homework_id,$user_id);
// 		var_dump($homeworkFeedbackInfo);
		if($homeworkFeedbackInfo){
			$homeworkImage=new homework_image();
			$homeworkImageInfo=$homeworkImage->getMyImageTotalByhomeworkFeedbackId($homeworkFeedbackInfo["id"]);
			$homeworkFeedbackInfo["image_count"]=($homeworkImageInfo["count"])?$homeworkImageInfo["count"]:0;
			$msg="获取成功！";
			$this->view->setState(1);
		}else{
			$msg="还没有反馈！";
			$this->view->setState(0);
		}
		$this->view->setData($homeworkFeedbackInfo);
		$this->view->setMsg($msg);
		$this->view->display("json");
	}
	/*学生对作业反馈图片
	 * 上传一张图片
	 * @para homework_id
	 * http://localhost/xdfServer/clientapi.php/homework/uploadHomeworkImage/
	 */
	public function Uploadhomeworkimage(){
		$msg 	="";
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
		$homework_id=$this->getRequest()->get("homework_id");
		//加载上传类
		$this->getApp()->loadUtilClass("UploadUtil");
		//设置上传类的参数（参数为数组）
		$upPara=array(
				'allowType'=>array("jpg","jpeg","gif","png","bmp","*"),//图片格式另定
				'maxsize'=>"20000000",//大小限制20M
				'israndname'=>true,
				'filepath'=>$this->uploadpath."image/"
		);
		$up=new uploadutil($upPara);
		if($up->uploadFile("image")){
			//$msg.="上传图片成功！";
			$imageName=$up->getNewFileName();
			//获取homework_feedback的id，如果没有则创建一条
			$homework_feedback=new homework_feedback();
			$homework_feedback_Info=$homework_feedback->getMyHomeworkFeedbackByHomeworkId($homework_id, $user_id);
			if(!$homework_feedback_Info["id"])
				$homework_feedback_id=$homework_feedback->addHomeworkFeedback($homework_id,$user_id);
			else 
				$homework_feedback_id=$homework_feedback_Info["id"];
			//保存一张图片
			$image=new image();
			if( $image_id=$image->addImage($imageName) ){
				//$msg="保存图片到数据库成功！";
				$homework_image=new homework_image;
				if($homework_image->addHomeworkImage($homework_feedback_id, $image_id)){
					//$msg.="保存反馈到数据库成功！";
					$msg.="上传图片成功！";
					$this->view->setState("1");
				}else {
					$this->view->setState("-1");
					$msg.=$homework_id."-".$homework_feedback_id."-".$image_id."-".$user_id."-保存反馈到数据库失败！";
				}
			}else
				//$msg="保存图片到数据库失败！";
				$msg.="上传图片出错了哟！";
		}else{
			$this->view->setState("-2");
			$up_error=$up->getErrorMsg();
			//$msg.="上传图片失败！".$up->$up_error;
			$msg.="上传图片失败！";
		}
		
		$this->view->setMsg($msg);
		$this->view->display("json");
	}

	//完成作业反馈,学生端上传作业图片反馈，点击确定按钮s
	public function finishHomeworkFeedback(){
		$msg 	="";
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
		$homework_id=$this->getRequest()->get("homework_id");
		$homework_feedback=new homework_feedback();
		if($homework_feedback->finishHomeworkFeedback($homework_id, $user_id)){
			$msg="操作成功！";
			$this->view->setState(1);
		}else{
			$msg="操作失败！";
			$this->view->setState(0);
		}
		$this->view->setData(null);
		$this->view->setMsg($msg);
		$this->view->display("json");
	}
	/**
	 * 获取作业反馈的列表
	 */
	public function getImageListByHomework(){
		$homework_id = $this->getRequest()->get('homework_id');
		$user_info = $this->getData ( 'userinfo' );
		$student_id = $user_info ['id'];
		$homework = new homework();
		$item = $homework->getFeedbackImageList($homework_id,$student_id);
		
		if ($item){
			$qiniu_path=$this->_app->getData("qiniu_path");
			foreach ($item as $key=>$val){
				$item[$key]['name_s'] =$qiniu_path["qiniu_path_image"].$item[$key]['name']."?imageView2/1/w/100/h/100";
				$item[$key]['name_b'] =$qiniu_path["qiniu_path_image"].$item[$key]['name'];
			}
			
			$data['list'] = $item;
			$data ['totalCount'] = count($item);
			$this->view->setState ( "1" );
			$this->view->setData ( $data );
			$this->view->setMsg ( "获取列表成功！" );
			$this->view->display ( "json" );
		} else {
			$data ['totalCount'] = "0";
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "没有更多了哟" );
			$this->view->display ( "json" );
		}
	}
	
	
	//无视频反馈到老师
// 	http://localhost/xdfServer/clientapi1.php/homework/FeedbackNoVideo/homework_id/44/item_id/33
	public function feedbackNoVideo(){
		$user_info = $this->getData ( 'userinfo' );
		$user_id = $user_info ['id'];
		$homework_id=$this->getRequest()->get("homework_id");
		$item_id=$this->getRequest()->get("item_id");
		//get teacher info
		$period=new period();
		$periodInfo=$period->getPeriodByHomeworkId($homework_id);
		$teacher_id=$periodInfo["teacher_id"];
		$user=new user();
		$phoneInfo=$user->getPhoneInfo($teacher_id);
		$message = new message();
		if($message->hasSentMessage($user_id, MessageCodeEnum::MESSAGE_TEA_NO_VIDEO, $item_id)){
			$msg="已经反馈过该题目无视频了，老师正在录制！";
			$this->view->setState("-1");
		}else{
			$result = $message->addMessage(
					MessageCodeEnum::MESSAGE_TEA_NO_VIDEO,
					$item_id,
					MessageCodeEnum::getCodes(MessageCodeEnum::MESSAGE_TEA_NO_VIDEO),
					$user_id,$teacher_id);
			if ($result){
				//set para for push to teacher
				$target = array(
						"type"=>$phoneInfo["type"],
						"ClientID"=>$phoneInfo["clientid"],
						"DeviceToken"=>$phoneInfo["devicetoken"]
				);
				$content = array(
						"info"=>'trans test透传',
						"title"=>'UDO学生端',
						"text"=>'howdo tester内容',
						"logo_url"=>$this->send_mes,
				);
				$this->push->pushToSingle($target, $content);
				$msg="反馈成功！";
				$this->view->setState("1");
			}else {
				$this->view->setState("0");
				$msg ="反馈失败！";
			}
		}
// 				$this->view->setState("1");
		$this->view->setMsg ( $msg );
		$this->view->setData(null);
		$this->view->display ( "json" ); 
	}
	
}
